package com.qf.lanzhou.blog.api.dao.Impl;

import com.qf.lanzhou.blog.api.dao.ArticleTypeDao;
import com.qf.lanzhou.blog.api.pojo.entity.Article;
import com.qf.lanzhou.blog.api.pojo.entity.Page;
import com.qf.lanzhou.blog.api.util.BeanProcessor;
import com.qf.lanzhou.blog.api.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author jack
 */
public class ArtivleTypeDaolmpl implements ArticleTypeDao {
    private QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
    @Override
    public List secletByType(Long i, Page page) {
        String sql = "SELECT * FROM t_article WHERE article_id IN" +
                " (SELECT article_id FROM r_article_tag WHERE tag_id = ?) LIMIT ?,?;";
        Object[] parm = {i,page.getStartRow(),page.getPageSize()};
        BeanListHandler handler = BeanProcessor.getBeanListHandler(Article.class);
        try {
            List query = (List) queryRunner.query(sql, handler, parm);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;

        }

    }

    @Override
    public Long selectTypeCount(Long type) {
        String sql = "SELECT COUNT(*) FROM t_article WHERE article_id IN " +
                "(SELECT article_id FROM r_article_tag WHERE tag_id = ?)";
        Object[] parm= {type};
        ScalarHandler<Long> handler = new ScalarHandler<>();
        try {
            Long query = queryRunner.query(sql, handler, parm);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
